import Taro from '@tarojs/taro'
import React, { Component, ReactNode } from "react";
import { View } from "@tarojs/components";
import "./statistics.less";
import config from "../../config.json";
import { AtList, AtListItem, AtNavBar, AtSegmentedControl } from 'taro-ui';
import { XScrollPicker } from "../../modal/component";
import { Bar, Column } from '@ant-design/charts';
import { ECharts } from "echarts";
import { Picker } from 'antd-mobile';

const startYear = 2021;
const startMonth = 10;

enum timeCurrentStringEnum {
    "month",
    "year"
}

class Statistics extends Component<any, any> {
    constructor(props: any) {
        super(props)
    }

    render() {
        return (
            <>
                <View>
                    <AtNavBar
                        onClickLeftIcon={() => { Taro.navigateBack() }}
                        color='#000'
                        title='会议室申请'
                        leftIconType="chevron-left"
                    />
                    <Overview />
                </View>
            </>
        )
    }
}

type OverviewState = {
    data: any[]
    query: any
    department: any[]
    mid: any[]
    uid: any[]
    isOpen: boolean
    time_current: number
    year: number
    selectMonth: number
    month: any[]
    mid_picker_visible: boolean
    uid_picker_visible: boolean
    department_picker_visible: boolean
}

class Overview extends Component<any, OverviewState> {
    years: any[];
    constructor(props: any) {
        super(props);
        this.years = getYears();
        const month = getMonth(this.years[this.years.length - 1]);
        this.state = {
            data: [],
            query: {
                department: "不限",
                uid: {
                    name: "不限",
                    uid: 0
                },
                mid: {
                    name: "不限",
                    mid: 0
                }
            },
            department: [],
            mid: [],
            uid: [],
            isOpen: false,
            time_current: 0,
            year: this.years.length - 1,
            selectMonth: month.length - 1,
            month: month,
            mid_picker_visible: false,
            uid_picker_visible: false,
            department_picker_visible: false
        };

    }

    async load(query?: any) {
        console.log("加载中");
        Taro.showLoading({ title: "加载中..." });
        try {
            let body: any = {};
            console.log(query)
            if (query) {
                if (query.department !== "不限" && query.department) {
                    body.department = query.department;
                }
                if (query.mid) {
                    body.mid = query.mid.mid;
                }
                if (query.uid) {
                    body.uid = query.uid.uid;
                }
                let start = new Date();
                let end = new Date();
                body.time = getQueryTimes.call(this, start, end, timeCurrentStringEnum[this.state.time_current]);
            }

            body.group = "day";
            let res = await Taro.request({
                url: config.domainName + '/agreed/statistics',
                method: 'POST',
                data: body,
                dataType: "json",
                header: {
                    token: Taro.getStorageSync('token'),
                },
            });
            if (!res.data.code) {
                this.setState({
                    data: res.data.data,
                })
            }

        } catch (err) {
            console.log(err);
            Taro.showToast({ title: "获取数据失败", icon: "error" as any });
        } finally {
            Taro.hideLoading();
        }
    }
    async loadSelector() {
        try {
            let dres = await Taro.request({
                url: config.domainName + '/department/query',
                method: "GET",
                data: {},
                header: {
                    token: Taro.getStorageSync('token'),
                }
            });
            const dpt = dres.data.data.map((value: { name: any; }) => {
                return value.name
            });
            dpt.push("不限");
            dpt.reverse();
            this.setState({
                department: dpt
            });
            let mres = await Taro.request({
                url: config.domainName + '/meetroom/query?search=&id=',
                method: "GET",
                data: {},
                header: {
                    token: Taro.getStorageSync('token'),
                }
            });
            let mid = mres.data.data.map((value: { mid: any; name: any; }) => {
                return {
                    mid: value.mid,
                    name: value.name
                }
            });
            mid.push({ name: "不限", mid: 0 });
            mid.reverse();
            this.setState({
                mid: mid
            });
            let ures = await Taro.request({
                url: config.domainName + '/user/admin/querylist',
                method: "GET",
                data: {},
                header: {
                    token: Taro.getStorageSync('token'),
                }
            });
            let uid = ures.data.data.map((value: { name: any; uid: any; }) => {
                return {
                    name: value.name,
                    uid: value.uid
                }
            });
            uid.push({ name: "不限", uid: 0 });
            uid.reverse();
            this.setState({
                uid: uid
            });

        } catch (err) {
            Taro.showToast({ title: "获取数据失败" });
        }

    }

    componentWillMount() {
        this.loadSelector();

    }

    componentDidMount() {
        let _this = this;
        this.load(_this.state.query);
    }

    componentWillUnmount() {

    }

    componentDidHide() { }

    handleChangeTime(a: string | number, b: { detail: { value: any; }; }) {
        this.setState((state) => {
            state.query[a] = b.detail.value;
            this.load(state.query);
            return state;
        })

    }

    handleChange(value: any, key: string) {
        this.setState((state) => {
            state.query[key] = value;
            this.load(state.query);
            return state;
        });
    }

    onReset() {
        this.setState({
            query: {}
        });
        this.load();
    }

    handleClose() {
        this.setState({
            isOpen: false
        })
    }
    handleOpen() {
        this.setState({
            isOpen: true
        })
    }
    handleClickTimeControl(res) {
        this.setState({ time_current: res });
        this.load(this.state.query);
    }

    handleChangeYear(year: number) {
        this.setState({
            year: year,
            month: getMonth(this.years[year]),
            selectMonth: getMonth(this.years[year]).length - 1
        });
        this.load(this.state.query);
    }

    handleChangeMonth(month: number) {
        this.setState({
            selectMonth: month
        })
        this.load(this.state.query);
    }

    getBarData() {
        let data = [];
        if (timeCurrentStringEnum[this.state.time_current] === "month") {
            this.state.data.forEach((item) => {
                let date = new Date(item.day);
                data.push({
                    count: item.count,
                    day: date.getDate() + "日"
                })
            });
        } else {
            for (let j = 0; j < 12; j++) {
                data.push({
                    count: 0,
                    day: j + 1 + "月"
                });
            }
            this.state.data.forEach((item) => {
                let date = new Date(item.day);
                data[date.getMonth()].count += item.count;
            });
        }
        return data;
    }

    render() {
        let sum = 0;
        let maxCount = 0;
        this.state.data.forEach((value) => {
            sum += value.count;
            if (value.count > maxCount) {
                maxCount = value.count;
            }
        });

        return (
            <>
                {/* <View style={{ display: "flex", justifyContent: "flex-end", padding: "10px 30px" }}>
                    <View onClick={this.handleOpen.bind(this)} className="primary-color-text" style={{ fontWeight: 600, fontSize: "0.8rem" }}>筛选</View>
                </View> */}


                <View className="header">
                    <View style={{ fontSize: "1rem", fontWeight: 900 }}>会议室总使用次数：</View>
                    <View style={{ textAlign: "right", fontSize: "60px", fontWeight: 900 }}>{sum}</View>
                </View>
                <AtList>
                    <AtListItem
                        title='系部'
                        extraText={this.state.query.department}
                        onClick={() => {
                            this.setState({
                                department_picker_visible: true
                            });
                        }}

                    />
                </AtList>
                <Picker
                    columns={[this.state.department]}
                    visible={this.state.department_picker_visible}
                    onClose={() => {
                        this.setState({
                            department_picker_visible: false
                        });
                    }}
                    onConfirm={(val) => {
                        this.handleChange(val[0], "department")
                    }}
                />
                <AtList>
                    <AtListItem
                        title='申请人'
                        extraText={this.state.query.uid ? this.state.query.uid.name : ""}
                        onClick={() => {
                            this.setState({
                                uid_picker_visible: true
                            });
                        }}
                    />
                </AtList>
                <Picker
                    columns={[this.state.uid.map((item) => {
                        return {
                            label: item.name,
                            value: item.uid
                        }
                    })]}
                    visible={this.state.uid_picker_visible}
                    onClose={() => {
                        this.setState({
                            uid_picker_visible: false
                        });
                    }}
                    onConfirm={(val) => {
                        let uid = val[0];
                        let value = {
                            uid: uid,
                            name: ""
                        };
                        for (let item of this.state.uid) {
                            if (item.uid === uid) {
                                value.uid = uid;
                                value.name = item.name;
                                break;
                            }
                        }
                        this.handleChange(value, "uid");
                    }}
                />
                <AtList>
                    <AtListItem
                        title='会议室'
                        extraText={this.state.query.mid ? this.state.query.mid.name : ""}
                        onClick={() => {
                            this.setState({
                                mid_picker_visible: true
                            });
                        }}

                    />
                </AtList>
                <Picker
                    columns={[this.state.mid.map((item) => {
                        return {
                            label: item.name,
                            value: item.mid
                        }
                    })]}
                    visible={this.state.mid_picker_visible}
                    onClose={() => {
                        this.setState({
                            mid_picker_visible: false
                        });
                    }}
                    onConfirm={(val) => {
                        let mid = val[0];
                        let value = {
                            mid: mid,
                            name: ""
                        };
                        for (let item of this.state.mid) {
                            if (item.mid === mid) {
                                value.mid = mid;
                                value.name = item.name;
                                break;
                            }
                        }
                        this.handleChange(value, "mid");
                    }}
                />
                <XScrollPicker
                    data={['按月', '按年']}
                    onChange={this.handleClickTimeControl.bind(this)}
                    value={this.state.time_current}
                />
                <XScrollPicker data={this.years} value={this.state.year} onChange={this.handleChangeYear.bind(this)} />
                {timeCurrentStringEnum[this.state.time_current] === "month" ? <XScrollPicker data={this.state.month} value={this.state.selectMonth} onChange={this.handleChangeMonth.bind(this)} /> : ""}

                {this.state.data.length ? <MyBar height={timeCurrentStringEnum[this.state.time_current] === "month" ? this.state.data.length * 1.5 + 2 : 16} data={((): any[] => {
                    return this.getBarData();
                })()}></MyBar> : <View style={{ margin: "1rem 0", textAlign: "center", color: "#aaa" }}>暂无信息</View>}

            </>

        )
    }
}


export default Statistics

type BarProps = {
    data: any[],
    height: number
}

// 柱状图
class MyBar extends Component<BarProps, any> {
    data: { type: string; sales: number; }[];
    config: any;
    constructor(props) {
        super(props);

    }
    componentDidMount() {

    }


    render() {
        let config = {
            data: this.props.data,
            xField: 'count',
            yField: 'day',
            barBackground: { style: { fill: 'rgba(0,0,0,0.1)' } },
            label: {
                position: "middle"
            },
            interactions: [
                {
                    type: 'active-region',
                    enable: false,
                },
            ],
            // scrollbar: { type: 'vertical' },
            minBarWidth: 20,
            barWidthRatio: 0.8,
        };
        return (
            <View style={{
                height: `${this.props.height}rem`,
                background: "#fff",
                marginBottom: "4rem",
                padding: "1rem 1rem 0 5px"
            }}>

                <Bar {...(config as any)} />
            </View>
        );
    }
}


function getYears() {
    const now = new Date().getFullYear();
    let years = [];
    for (let i = startYear; i <= now; i++) {
        years.push(i);
    }
    return years;
}

function getMonth(year: number) {
    const now = new Date();
    let month = [];
    if (now.getFullYear() === year && startYear === year) {
        for (let i = startMonth; i <= now.getMonth() + 1; i++) {
            month.push(`${i}月`);
        }
    } else if (now.getFullYear() !== year && startYear === year) {
        for (let i = startMonth; i <= 12; i++) {
            month.push(`${i}月`);
        }
    } else if (now.getFullYear() !== year && startYear !== year) {
        for (let i = 1; i <= 12; i++) {
            month.push(`${i}月`);
        }
    } else {
        for (let i = 1; i <= now.getMonth() + 1; i++) {
            month.push(`${i}月`);
        }
    }
    return month;
}


const getdaynum = (month: number, year: number) => {
    const big = new Set([1, 3, 5, 7, 8, 10, 12]);
    const small = new Set([2, 4, 6, 9, 11]);
    if (big.has(month)) {
        return 31;
    } else if (year % 4 === 0 && month === 2) {
        return 29;
    } else if (month === 2) {
        return 28;
    } else {
        return 30;
    }
}
function getQueryTimes(start: Date, end: Date, type: string): [number, number] {
    const rtn: [number, number] = [0, 0];
    start.setFullYear(parseInt(this.years[this.state.year]));
    if (type === "month") {
        start.setMonth(parseInt(this.state.month[this.state.selectMonth].split("月")[0]) - 1);
        end.setMonth(parseInt(this.state.month[this.state.selectMonth].split("月")[0]) - 1);
    } else {
        start.setMonth(0);
        end.setMonth(11);
    }
    start.setDate(1);
    start.setHours(0);
    start.setMinutes(0);
    start.setSeconds(0);
    end.setFullYear(parseInt(this.years[this.state.year]));
    end.setDate(getdaynum(end.getMonth() + 1, start.getFullYear()));
    end.setHours(0);
    end.setMinutes(0);
    end.setSeconds(0);
    rtn[0] = start.getTime();
    rtn[1] = end.getTime();
    return rtn;
}